<?php

require_once ('Joob/Controller/Front.php');

class Joob_Bootstrap {
	
	protected $frontController;
	
	protected $registry;
	
	protected $setupSections;
	
	public function __construct() {
		$this->setupSections = array ('Registry', 'FrontController', 'AutoLoader', 'Session');
		$this->setup ();
	}
	
	/**
	 * A wrapper for the registry so that client dont have to include it
	 * @param unknown_type $key the key
	 * @param unknown_type $value the value
	 * @param unknown_type $namespace the key namespace
	 */
	public function setKey($key, $value, $namespace = "Joob") {
		$this->registry->store ( $key, $value, $namespace );
	}
	
	public function setupSession()	{
		require_once 'Joob/Session/Storage/Standard.php';
		$storage = new Joob_Session_Storage_Standard();
		
		require_once 'Joob/Session/Behaviour/Namespace.php';
		$behaviour = new Joob_Session_Behaviour_Namespace($storage);

		$this->registry->store('behaviour', $behaviour, 'Joob:session');
		
		$session = Joob_Session_Standard::getInstance();
		$session->start();
	}
	
	public function setupAutoLoader()	{
		require_once 'Joob/Loader/Autoloader.php';
		$loader = Joob_Loader_Autoloader::getInstance();
		$loader->defaultAutoLoader();
		spl_autoload_register(array($loader, 'autoload'));
	}
	
	public function setupRegistry() {
		require_once 'Joob/Registry/KVP.php';
		$this->registry = Joob_Registry_KVP::getInstance ();
		
		//setup request parser
		require_once 'Joob/Http/Request/Parser/Parameters.php';
		$this->registry->store ( 'parser', new Joob_Http_Request_Parser_Parameters (), 'Joob:http:request' );
	}
	
	public function setupFrontController() {
		require_once 'Joob/Controller/Front.php';
		$this->frontController = new Joob_Controller_Front ();
		
		require_once 'Joob/Controller/Dispatcher.php';
		$this->frontController->setDispatcher ( new Joob_Controller_Dispatcher () );
	}
	
	/**
	 * Setup/Initialize variables
	 */
	protected function setup() {
		//call requested setup functions
		foreach ($this->setupSections as $section) {
			$methodName = 'setup'.$section;
			if (is_callable(array($this, $methodName)))	{
				call_user_func_array(array($this, $methodName), array());
			}
		}
	}
	
	public function run() {
		$this->frontController->dispatch ();
	}
}

?>